from rest_framework import serializers
from .models import StockIn, StockInDetail, StockOut, StockOutDetail, StockRecord, StockCheck, StockCheckDetail, StockTransfer, StockTransferDetail
from product.serializers import ProductSerializer
from supplier.serializers import SupplierSerializer
from customer.serializers import CustomerSerializer
from employee.serializers import EmployeeSerializer
from .utils import generate_stock_in_no, generate_stock_out_no, generate_stock_check_no, generate_stock_transfer_no
from supplier.models import Supplier
from product.models import Product

class StockInDetailSerializer(serializers.ModelSerializer):
    product = ProductSerializer(read_only=True)
    product_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = StockInDetail
        fields = ['id', 'product', 'product_id', 'price', 'quantity', 'amount']
        read_only_fields = ['id', 'amount']

    def validate_price(self, value):
        if value <= 0:
            raise serializers.ValidationError('价格必须大于0')
        return value

    def validate_quantity(self, value):
        if value <= 0:
            raise serializers.ValidationError('数量必须大于0')
        return value

    def create(self, validated_data):
        validated_data['amount'] = validated_data['price'] * validated_data['quantity']
        return super().create(validated_data)

class StockInSerializer(serializers.ModelSerializer):
    details = StockInDetailSerializer(many=True)
    supplier = SupplierSerializer(read_only=True)
    supplier_id = serializers.IntegerField(write_only=True)
    create_user = EmployeeSerializer(read_only=True)

    class Meta:
        model = StockIn
        fields = ['id', 'stock_in_no', 'supplier', 'supplier_id', 'total_amount',
                 'status', 'create_user', 'create_time', 'update_time', 'details']
        read_only_fields = ['id', 'stock_in_no', 'total_amount', 'create_time', 'update_time']

    def validate_supplier_id(self, value):
        try:
            Supplier.objects.get(id=value)
        except Supplier.DoesNotExist:
            raise serializers.ValidationError('供应商不存在')
        return value

    def validate_details(self, value):
        if not value:
            raise serializers.ValidationError('入库明细不能为空')

        # 检查商品是否存在
        for detail in value:
            try:
                Product.objects.get(id=detail['product_id'])
            except Product.DoesNotExist:
                raise serializers.ValidationError(f'商品ID {detail["product_id"]} 不存在')

            if detail['price'] <= 0:
                raise serializers.ValidationError('入库价格必须大于0')

            if detail['quantity'] <= 0:
                raise serializers.ValidationError('入库数量必须大于0')

        return value

    def create(self, validated_data):
        details_data = validated_data.pop('details')
        validated_data['stock_in_no'] = generate_stock_in_no()
        validated_data['create_user'] = self.context['request'].user
        stock_in = StockIn.objects.create(**validated_data)
        total_amount = 0

        for detail_data in details_data:
            detail_data['stock_in'] = stock_in
            amount = detail_data['price'] * detail_data['quantity']
            detail_data['amount'] = amount
            total_amount += amount
            StockInDetail.objects.create(**detail_data)

        stock_in.total_amount = total_amount
        stock_in.save()
        return stock_in

class StockOutDetailSerializer(serializers.ModelSerializer):
    product = ProductSerializer(read_only=True)
    product_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = StockOutDetail
        fields = ['id', 'product', 'product_id', 'price', 'quantity', 'amount']
        read_only_fields = ['id', 'amount']

    def validate_price(self, value):
        if value <= 0:
            raise serializers.ValidationError('价格必须大于0')
        return value

    def validate_quantity(self, value):
        if value <= 0:
            raise serializers.ValidationError('数量必须大于0')
        return value

class StockOutSerializer(serializers.ModelSerializer):
    details = StockOutDetailSerializer(many=True)
    customer = CustomerSerializer(read_only=True)
    customer_id = serializers.IntegerField(write_only=True)
    create_user = EmployeeSerializer(read_only=True)

    class Meta:
        model = StockOut
        fields = ['id', 'stock_out_no', 'customer', 'customer_id', 'total_amount', 
                 'status', 'create_user', 'create_time', 'update_time', 'details']
        read_only_fields = ['id', 'stock_out_no', 'total_amount', 'create_time', 'update_time']

    def validate_details(self, value):
        if not value:
            raise serializers.ValidationError('出库明细不能为空')
        return value

    def create(self, validated_data):
        details_data = validated_data.pop('details')
        validated_data['stock_out_no'] = generate_stock_out_no()
        validated_data['create_user'] = self.context['request'].user
        stock_out = StockOut.objects.create(**validated_data)
        total_amount = 0
        
        for detail_data in details_data:
            detail_data['stock_out'] = stock_out
            amount = detail_data['price'] * detail_data['quantity']
            detail_data['amount'] = amount
            total_amount += amount
            StockOutDetail.objects.create(**detail_data)
        
        stock_out.total_amount = total_amount
        stock_out.save()
        return stock_out

class StockRecordSerializer(serializers.ModelSerializer):
    """库存流水记录序列化器"""
    product_name = serializers.CharField(source='product.name', read_only=True)
    product_code = serializers.CharField(source='product.code', read_only=True)
    type_display = serializers.CharField(source='get_type_display', read_only=True)
    create_user_name = serializers.CharField(source='create_user.name', read_only=True)
    
    class Meta:
        model = StockRecord
        fields = ['id', 'product', 'product_name', 'product_code', 'type', 'type_display',
                 'quantity', 'before_stock', 'after_stock', 'related_no', 'remark',
                 'create_user', 'create_user_name', 'create_time']
        read_only_fields = ['id', 'create_time']

class StockCheckDetailSerializer(serializers.ModelSerializer):
    """库存盘点单明细序列化器"""
    product = ProductSerializer(read_only=True)
    product_id = serializers.IntegerField(write_only=True)
    system_stock = serializers.IntegerField(read_only=True)

    class Meta:
        model = StockCheckDetail
        fields = ['id', 'product', 'product_id', 'system_stock', 'actual_stock', 
                 'difference', 'amount', 'remark']
        read_only_fields = ['id', 'system_stock', 'difference', 'amount']

    def validate_actual_stock(self, value):
        if value < 0:
            raise serializers.ValidationError('实际库存不能小于0')
        return value

class StockCheckSerializer(serializers.ModelSerializer):
    """库存盘点单序列化器"""
    details = StockCheckDetailSerializer(many=True)
    create_user = EmployeeSerializer(read_only=True)

    class Meta:
        model = StockCheck
        fields = ['id', 'check_no', 'total_amount', 'status', 'remark',
                 'create_user', 'create_time', 'update_time', 'details']
        read_only_fields = ['id', 'check_no', 'total_amount', 'create_time', 'update_time']

    def validate_details(self, value):
        if not value:
            raise serializers.ValidationError('盘点明细不能为空')
        return value

    def create(self, validated_data):
        details_data = validated_data.pop('details')
        validated_data['check_no'] = generate_stock_check_no()
        validated_data['create_user'] = self.context['request'].user
        stock_check = StockCheck.objects.create(**validated_data)
        total_amount = 0
        
        for detail_data in details_data:
            product = Product.objects.get(id=detail_data['product_id'])
            detail_data['stock_check'] = stock_check
            detail_data['system_stock'] = product.stock
            detail_data['difference'] = detail_data['actual_stock'] - product.stock
            # 使用商品成本价计算差异金额
            detail_data['amount'] = detail_data['difference'] * product.purchase_price
            total_amount += detail_data['amount']
            StockCheckDetail.objects.create(**detail_data)
        
        stock_check.total_amount = total_amount
        stock_check.save()
        return stock_check

class StockTransferDetailSerializer(serializers.ModelSerializer):
    """调拨单明细序列化器"""
    product_detail = ProductSerializer(source='product', read_only=True)
    product_id = serializers.IntegerField(write_only=True)
    
    class Meta:
        model = StockTransferDetail
        fields = ['id', 'product_id', 'product_detail', 'quantity', 'remark']
        read_only_fields = ['id']
    
    def validate_quantity(self, value):
        if value <= 0:
            raise serializers.ValidationError('调拨数量必须大于0')
        return value

class StockTransferSerializer(serializers.ModelSerializer):
    """调拨单序列化器"""
    details = StockTransferDetailSerializer(many=True)
    creator_detail = EmployeeSerializer(source='create_user', read_only=True)
    
    class Meta:
        model = StockTransfer
        fields = ['id', 'transfer_no', 'from_warehouse', 'to_warehouse', 'status', 
                 'remark', 'create_user', 'creator_detail', 'details', 'create_time', 'update_time']
        read_only_fields = ['id', 'transfer_no', 'create_user', 'create_time', 'update_time']
    
    def validate_details(self, value):
        if not value:
            raise serializers.ValidationError('调拨单明细不能为空')
        return value
    
    def create(self, validated_data):
        details_data = validated_data.pop('details')
        validated_data['transfer_no'] = generate_stock_transfer_no()
        validated_data['create_user'] = self.context['request'].user
        
        stock_transfer = StockTransfer.objects.create(**validated_data)
        
        for detail_data in details_data:
            StockTransferDetail.objects.create(stock_transfer=stock_transfer, **detail_data)
        
        return stock_transfer 